package com.yuyang.wifi.utils;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Build;

import androidx.annotation.RequiresApi;


/**
 * created by mej
 * on 2021/4/23
 */
public class DeviceChargeUtils {


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public static int getCurrentChargeLevel(Context context) {
        try {
            BatteryManager manager = (BatteryManager) context.getSystemService(context.BATTERY_SERVICE);
            int currentLevel = manager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
            return currentLevel;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static boolean isChargingState(Context context) {
        IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatusIntent = context.registerReceiver(null, ifilter);
        //如果设备正在充电，可以提取当前的充电状态和充电方式（无论是通过 USB 还是交流充电器），如下所示：
        // Are we charging / charged?
        int status = batteryStatusIntent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                status == BatteryManager.BATTERY_STATUS_FULL;
        // How are we charging?
//        int chargePlug = batteryStatusIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
//        boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
//        boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;

        if (isCharging) {
//            if (usbCharge) {
//                //Toast.makeText(MainActivity.this, "手机正处于USB连接！", Toast.LENGTH_SHORT).show();
//                return true;
//            } else if (acCharge) {
//                //Toast.makeText(MainActivity.this, "手机通过电源充电中！", Toast.LENGTH_SHORT).show();
//                return true;
//            }
            return true;
        } else {
            //Toast.makeText(MainActivity.this, "手机未连接USB线！", Toast.LENGTH_SHORT).show();
            return false;
        }
    }

}
